<template>
  <div class="salary">
    <div>
      <el-date-picker v-model="month" type="month" value-format="timestamp" placeholder="选择月"></el-date-picker>
      <el-button style="margin-left:10px" type="primary" class="add-btn" @click="searchResult">当月入会用户和绩效计算</el-button>
    </div>
    <el-tabs v-model="activeName" @tab-click="switchTab" v-if="currentMonthUsers.length">
      <el-tab-pane label="当月入会用户" name="0">
        <p>当月入会用户共计{{currentMonthUsers.length}}人</p>
        <el-table :data="currentMonthUsers" style="width: 100%">
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="parentName" label="上级姓名"></el-table-column>
          <el-table-column prop="price" label="入会金额"></el-table-column>
          <el-table-column prop="date" label="日期">
            <template slot-scope="scope">{{scope.row.date|formatDate}}</template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="当月工资核算" name="1">
        <el-table :data="salaryArr" style="width: 100%">
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="totalSalary" label="工资"></el-table-column>
        </el-table>
        <p class="total-price">当月工资共计: <span>{{totalPrice}}</span>元</p>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
/* eslint-disable */
import moment from "moment";
export default {
  name: "salary",
  filters: {
    formatDate(value) {
      return moment(value).format("YYYY-MM-DD");
    }
  },
  data() {
    return {
      month: "",
      activeName: "0",
      currentMonthUsers: [],
      salaryObj: {},
      salaryArr: [],
      treeData: [],

    };
  },
  created() {
    this.userData = [];
    this.$store.state.userData.forEach(item => {
      this.userData.push(Object.assign({}, item));
    });
  },
  computed: {
    totalPrice() {
      return this.salaryArr.reduce((pre, cur) => {
        console.log(cur,pre);
        return cur.totalSalary + pre;
      }, 0)
    }
  },
  methods: {
    searchResult() {
      if (!this.month) {
        this.$message({
          message: "请选择月份",
          type: "warning"
        });
        return false;
      }
      const days = moment(this.month).daysInMonth();
      let endDate = this.month + days * 3600 * 1000 * 24;
      this.activeName = "0";
      this.userData = [];
      this.$store.state.userData.forEach(item => {
        this.userData.push(Object.assign({}, item));
      });
      this.currentMonthUsers = this.userData.filter(user => {
        return user.date >= this.month && user.date < endDate;
      });
      this.salaryObj = {};
      this.treeData = this.formatTreeData(this.userData);
      this.countSalary(endDate);
      for (let n in this.salaryObj) {
        this.salaryArr.push(this.salaryObj[n]);
      }
    },
    countSalary(endDate) {
      let treeData = JSON.parse(JSON.stringify(this.treeData));
      this.currentMonthUsers.map(user => {
        // let parentNodes = this.findAllParent({ id: user.id, parentId: user.parentId },
        //   treeData,
        //   []
        // );
        // 如果是顶级节点 直接返回
        if (user.parentId === '') {
          return;
        }
        // 获取当前用户所在的节点树
        let currentTree = treeData.find(child => {
          let node = [];
          this.findUser(user.id, [child], node);
          return node.length;
        })
        // 百分之三十提成
        let res = this.countOneSalary(user.parentId, currentTree, 0.3);
        if (res.isEnd) return;
        // 百分之十提成
        res = this.countOneSalary(res.id, currentTree, 0.1);
        if (res.isEnd) return;
        res = this.countOneSalary(res.id, currentTree, 0.03, true, endDate);
        if (res.isEnd) return;
        res = this.countOneSalary(res.id, currentTree, 0.02, true, endDate);
        // node = this.findParent(node.parentId, [currentTree]);
        // if (!this.salaryObj[node.id]) {
        //   this.salaryObj[node.id] = {};
        //   this.salaryObj[node.id]['name'] = node.name;
        //   this.salaryObj[node.id]['totalSalary'] = 0;
        // }
        // this.salaryObj[node.id]['totalSalary'] += node.price * 0.1;

      });
      console.log(this.salaryObj);
    },
    countOneSalary(id, tree, percent, condition = false, endDate) {
      let node;
      if (!condition) {
        node = this.findParent(id, [tree]);
      } else {
        // let isEnd = false;
        while (id !== '') {
          node = this.findParent(id, [tree]);
          if (node.children && node.children.length > 2) {
            let arr = node.children.filter(item => {
              return item.date < endDate;
            })
            if (arr.length > 2) {
              break;
            } else {
              id = node.parentId;
            }
          } else {
            id = node.parentId;
          }
        }
        if (id === '') return { id, isEnd: true };
      }
      if (!this.salaryObj[node.id]) {
        this.salaryObj[node.id] = {};
        this.salaryObj[node.id]['name'] = node.name;
        this.salaryObj[node.id]['totalSalary'] = 0;
      }
      this.salaryObj[node.id]['totalSalary'] += node.price * percent;
      return { id: node.parentId, isEnd: node.parentId === '' ? true : false };
    },
    switchTab() {},
    formatTreeData(userData) {
      const formatData = [];
      const getChildren = function(pid, arr) {
        userData.forEach(item => {
          if (item.parentId === pid) {
            if (pid) {
              if (!arr.children) {
                arr.children = [];
              }
              arr.children.push(item);
            } else {
              arr.push(item);
            }
            getChildren(item.id, item);
          }
        });
      };
      getChildren("", formatData);
      return formatData;
    },
    findParent(id, tree) {
      for (let i = 0; i < tree.length; i++) {
        let item = tree[i];
        if (id === item.id) {
          return item;
        }
        if (item.children && item.children.length) {
          return this.findParent(id, item.children);
        } else {}
        // return id === item.id ? item.id : this.findParent(id,item.children?item.children:[]);
      }
    },
    findUser(id, tree, node) {
      for (let i = 0; i < tree.length; i++) {
        let item = tree[i];
        if (id === item.id) {
          node.push(item);
          return;
        }
        if (item.children && item.children.length) {
          this.findUser(id, item.children, node);
        } else {}
      }
    }
  }
};
</script>
<style lang="less" scoped>
.salary {
  margin: 10px;
}
.total-price {
  text-align: right;

  margin-top:20px;
  span {
    color:red;
    font-size: 2em;
  }
}
</style>